<template>
    <div class="poster_box">
        <el-form
            ref="formRef"
            :rules="pageType == 'look' ? '' : rules"
            :model="formData"
            label-width="80px"
            :disabled="pageType == 'look'">
            <poster-settings
                ref="posterSettingsRefs"
                v-model="formData.poster"
                default-url="https://static.scrm.keyid.cn/assets/images/web-pc/default-fission-poster.png"
                :disabled="pageType == 'look'" />
            <el-form-item v-if="create_type == 2" label="海报生成" style="margin-top: 20px">
                <div class="poster_keywords">
                    <el-form-item label="活动触发关键词：" prop="keywords" label-width="140px">
                        <el-input
                            v-model.trim="formData.keywords"
                            placeholder="关键词"
                            maxlength="10"
                            show-word-limit
                            @blur="handleKeyWordsBlur" />
                        <span>公众号回复关键词可参与活动</span>
                    </el-form-item>

                    <el-form-item label="参与活动提示语：" prop="activity_clues" label-width="140px">
                        <tinymce-editor
                            id="editor"
                            ref="editorRef"
                            v-model:value="formData.activity_clues"
                            style="width: 100%"
                            :config="editorConfig"></tinymce-editor>
                        <div v-if="formData.keywords" class="mt8">
                            点击插入 <span class="key_tag" @click="doInsertTag"> {{ formData.keywords }} </span>
                        </div>
                    </el-form-item>
                    <el-form-item label="活动规则描述：" prop="activity_rule_desc" label-width="140px">
                        <el-input
                            model-value="关注后推送【活动描述规则+员工二维码】"
                            class="activity_rule_desc_input"
                            readonly />
                        <el-input
                            v-model="formData.activity_rule_desc"
                            maxlength="500"
                            :rows="9"
                            class="desc_input"
                            placeholder="请输入活动规则描述"
                            show-word-limit
                            type="textarea" />
                    </el-form-item>
                </div>
            </el-form-item>
        </el-form>
        <div class="right_box">
            <poster-phone
                ref="activityPhoneRef"
                v-model:url="formData.poster.absolute_url"
                :disabled="pageType == 'look'"
                class="poster-phone"
                :poster-head="formData.poster.avatar_type"
                :poster-head-switch="formData.poster.avatar_flag"
                :poster-nickname-color="formData.poster.nickname_color"
                :poster-nickname-size="formData.poster.nickname_size"
                :poster-nickname-switch="formData.poster.nickname_flag"
                :poster-desc-color="formData.poster.desc_color"
                :poster-desc-switch="formData.poster.desc_flag"
                :poster-desc-content="formData.poster.desc"
                :poster-desc-size="formData.poster.desc_size" />
        </div>
    </div>

    <ChoosePoster ref="ChoosePosterRef" @save="getPoster" />
</template>

<script setup lang="ts">
import { ref, reactive, defineExpose, defineProps, withDefaults, onMounted, inject } from 'vue';
import { ElMessage } from 'element-plus';
import { uploadFile2 } from '@/api/common';
import ChoosePoster from '@/view/content/highMaterial/poster/components/ChoosePoster.vue';
import type { FormInstance, FormRules } from 'element-plus';
import TinymceEditor from '@/components/TinymceEditor.vue';
import PosterPhone from '@/components/zw/phonePreview1.0/activityPhonePreview/posterPhone/index.vue';
import PosterSettings from '@/components/zw/activity/poster-settings/index.vue';

import { useRoute } from 'vue-router';

interface Props {
    pageType: any;
}
withDefaults(defineProps<Props>(), {
    pageType: ''
});
const route = useRoute();
const emit = defineEmits(['submit']);
const ChoosePosterRef: any = ref(null);
const activeName = ref('企业微信');
const formRef = ref<any>();
const formData = ref({
    poster_type: 1, // 海报类型
    keywords: '', // 关键字
    activity_rule_desc: '',
    activity_clues: '',
    code: '', // 本地上传
    poster: {
        poster_type: 0, //0: 默认海报， 1: 海报库， 2: 本地上传
        poster_id: undefined, //海报库中海报id
        absolute_url: 'https://static.scrm.keyid.cn/assets/images/web-pc/default-fission-poster.png', //海报图片url
        poster_absolute_url: '', // 海报库中海报url
        local_absolute_url: '', // 本地海报上传url
        avatar_flag: 1, //是否用户头像 1: 打开， 2: 关闭
        avatar_type: 1, //头像展示类型  1: 圆形, 2: 方形
        nickname_flag: 1, //是否用户昵称  1: 打开， 2: 关闭
        nickname_color: '#ffffff', //用户昵称颜色
        nickname_size: 14, //用户昵称字体大小
        desc_flag: 1, //是否描述 1: 打开， 2: 关闭
        desc_color: '#ffffff', //描述颜色
        desc_size: 12, //描述字体大小
        desc: '' //描述内容
    }
});

const activityPhoneRef = ref<any>(null);

// 校验关键字
const keywordsValidator = (rule: any, value: any, callback: any) => {
    if (!value) return callback(new Error('请输入关键字'));
    const reg = /^[\u4e00-\u9fa5a-zA-Z0-9][\u4e00-\u9fa5a-zA-Z0-9]*$/;
    if (!reg.test(value)) {
        callback(new Error('仅支持中文、英文、数字'));
    } else {
        callback();
    }
};

// 校验活动提示语
const activityCluesValidator = (rule: any, value: any, callback: any) => {
    if (!value) return callback(new Error('请输入活动提示语'));
    // 处理参与活动提示语
    const dom: HTMLDivElement | null = document.createElement('div');
    dom.innerHTML = value;
    const keyTagDom = `<span class="key_tag" contenteditable="false">【${formData.value.keywords}】</span>`;
    if (dom.innerText.length > 500) {
        callback(new Error('最多支持500个字符'));
    } else if (!dom.innerHTML.includes(keyTagDom)) {
        callback(new Error('请插入活动提示语关键字！'));
    } else {
        callback();
    }
};

const rules = reactive<FormRules>({
    code: [{ required: true, message: '请上传海报', trigger: 'change' }],
    poster_id: [{ required: true, message: '请选择海报', trigger: 'change' }],
    poster_type: [{ required: true, message: '请选择海报类型', trigger: 'change' }],
    poster_head_switch: [{ required: true, message: '请选择头像形状', trigger: 'change' }],
    poster_nickname_switch: [{ required: true, message: '请选择昵称颜色大小', trigger: 'change' }],
    keywords: [{ required: true, validator: keywordsValidator, trigger: 'change' }],
    activity_rule_desc: [{ required: true, message: '请输入活动规则描述', trigger: 'change' }],
    activity_clues: [{ required: true, validator: activityCluesValidator }]
});

/* ================================海报生成关键字模板================================ */
const create_type = inject('create_type');
// 覆盖富文本的配置项
const editorConfig = {
    height: 200,
    menubar: false,
    statusbar: false,
    toolbar: false,
    plugins: '', // 插件
    content_css: '/tinymce/skins/content/content_css/index.css',
    init_instance_callback: function (editor: any) {
        if (route.query.type === 'look') editorRef.value?.tinymceEditors['editor']?.setMode('readonly');
    }
};
// 富文本
const editorRef = ref();
// 插入标签
const doInsertTag = () => {
    if (route.query.type === 'look') return;
    const tag = document.createElement('span');
    tag.setAttribute('contenteditable', 'false');
    tag.innerText = `【${formData.value.keywords}】`;
    tag.className = 'key_tag';
    editorRef.value.tinymceEditors['editor'].insertContent(tag.outerHTML);
};
//关键字输入完毕后，动态更新富文本内容
const handleKeyWordsBlur = () => {
    const reg = /\<span class="key_tag" contenteditable="false">(【.+?】)<\/span\>/g;
    const keyTagDom = `<span class="key_tag" contenteditable="false">【${formData.value.keywords}】</span>`;
    formData.value.activity_clues = formData.value.activity_clues.replace(reg, keyTagDom);
};
/* ================================海报生成关键字模板================================ */

// 选择海报库
const onPoster = () => {
    ChoosePosterRef.value.appDialog.visible = true;
};
const getPoster = (val: any) => {
    formData.value.poster_id = val.idList[0];
    formData.value.absolute_url = val.list[0].poster_url;
    formData.value.code = '';
    // postersURL.value = val.list[0].poster_url;
};
// 上传海报
const uploadFun = async (file: any, fileName: string) => {
    const res = await uploadFile2({ file, fileName });
    formData.value.code = res.code;
    formData.value.absolute_url = res.url;
    formData.value.poster_id = '';
};
// 本地上传
const beforeAvatarUpload = (rawFile: any) => {
    if (rawFile.size / 1024 / 1024 > 10) {
        ElMessage.error('上传图片大小不能超过10M');
        return false;
    }
    uploadFun(rawFile.raw, rawFile.name);
};
const element: any = ref(null);
const str = ref('avatar');

//当鼠标弹起的时候，移除 move 事件
document.onmouseup = function () {
    document.onmousemove = null;
};
const onSubmit = async () => {
    if (!formRef.value) return;
    await formRef.value.validate(async (valid: any, fields: any) => {
        const result = await getPosterForms();
        if (result === false) return;
        formData.value.poster = result;
        if (valid) {
            emit('submit');
        } else {
            ElMessage.warning(Object.values(fields)[0][0].message);
        }
    });
};

const setPosition = (val: any) => {
    activityPhoneRef.value.formData.position = val;
};
const getPostersInfo = () => {
    return activityPhoneRef.value.formData;
};

/* ----------------------------海报设置-start---------------------------- */
const posterSettingsRefs = ref();

const getPosterForms = async () => {
    return await posterSettingsRefs.value.getFormParams();
};
/* ----------------------------海报设置-end---------------------------- */

defineExpose({
    onSubmit,
    formData,
    setPosition,
    getPostersInfo
});
</script>

<style lang="scss" scoped>
// 颜色选择器
:deep .el-color-picker__empty {
    font-size: 0;
}

:deep .el-color-picker__trigger {
    border: none;
}

:deep .el-color-picker__color {
    // border: none;
    border: 1px solid #eeebee;
}

.poster_box {
    display: grid;
    grid-template-columns: 1.2fr 1fr;
    margin-bottom: 20px;

    .right_box {
        display: grid;
        justify-content: center;

        .poster_right_box {
            width: 360px;
            height: 640px;
            padding: 15px;
            background-color: #f3fafb;
            border: solid 2px #d2d8db;

            .content {
                position: relative;
                width: 100%;
                height: 100%;
                background-color: #fff;
                border-radius: 20px;
                background-size: cover;

                .avatar_box {
                    width: 50px;
                    height: 50px;
                    position: absolute;
                    top: 572px;
                    left: 17px;
                    cursor: move;

                    img {
                        width: 100%;
                        height: 100%;
                        background-color: pink;
                    }
                }

                .nickname_box {
                    position: absolute;
                    top: 588px;
                    left: 77px;
                    cursor: move;
                }

                .qrcode_box {
                    position: absolute;
                    left: 265px;
                    top: 550px;
                    z-index: 3;
                    cursor: move;
                    width: 80px;
                    height: 80px;

                    img {
                        width: 100%;
                        height: 100%;
                    }
                }
            }
        }
    }
}

.poster_keywords {
    padding: 24px;
    border: 1px solid #eaeaea;

    .key_tag {
        cursor: pointer;
        display: inline-block;
        user-select: none;
        line-height: 1;
        margin-left: 8px;
        padding: 6px 12px;
        background-color: #fff2e9;
        border-radius: 2px;
        border: 1px solid #ffc69e;
        color: #ff6b00;
    }

    .el-form-item {
        margin-bottom: 24px;
    }

    .el-input {
        margin-right: 6px;
        width: 288px;
        display: inline-block;
    }

    .activity_clues {
        height: 200px;
        padding: 4px 15px;
        line-height: 1.5;
        background-color: #f9f9f9;
        border-radius: 5px;
        border: 1px solid #eaeaea;

        &:focus-visible {
            border: 1px solid #ff6b00;
            outline: none;
        }
    }

    .el-textarea {
        :deep(.el-textarea__inner) {
            background: #f9f9f9;
            border-radius: 4px;
            border: 1px solid #eaeaea;
        }
    }

    :deep(.tox-tinymce) {
        border: none;
    }

    :deep(.tox-edit-area__iframe) {
        background: #f9f9f9;
        border-radius: 4px;
        border: 1px solid #eaeaea;
    }

    .activity_rule_desc_input {
        margin-bottom: 16px;

        :deep(.el-input__wrapper) {
            width: 100%;
        }
    }

    .desc_input {
        :deep(.el-textarea__inner) {
            border: none !important;
        }
    }
}

.l_h {
    :deep(.el-form-item__content) {
        line-height: 0px;
    }

    // margin-bottom: 10px;
}

.m_t {
    margin-top: 10px;
}

.mt8 {
    margin-top: 8px;
}

.el-form-item {
    margin-bottom: 0;
}

.imgText {
    margin-top: 10px;
    font-size: 12px;
    font-weight: 300;
    color: #969696;
}
</style>
